import VueRouter from "vue-router";
import Login from "@/views/Login.vue";
import Users from "@/views/Users.vue";
import Main from '@/views/Main.vue'
import Home from "@/views/Home.vue";
import Mall from "@/views/Mall.vue";
import PageOne from "@/views/Pay.vue";
import Cookie from "js-cookie";

const router= new VueRouter({
    // 浏览器模式设置，设置为history模式
    // mode:'history',
    routes:[
        {
            name:'login',
            path:"/login",
            component:Login,
            meta:{title:"登录"},
        },
        {
            // 子路由
            name:"main",
            path:'/',
            redirect:"/home",  //重定向 当路径为/，则重定向home
            component:Main,
            children:[
                {
                    name:"user",
                    path:"user",
                    component:Users,
                    meta:{title:"用户管理"}
                },
                {
                    name:"home",
                    path:"home",
                    component:Home,
                    meta:{title:"首页"}
                },
                {
                    name:"mall",
                    path:"mall",
                    component:Mall,
                    meta:{title:"商品管理"}
                },
                {
                    name:"pay",
                    path:"pay",
                    component:PageOne,
                    meta:{title:"支付管理"}
                }               
            ]
        }

    ]
})

//添加全局前置导航守卫
router.beforeEach((to,from,next)=>{
  //判断token存不存在
  const token=Cookie.get('token')
  //token不存在，说明当前用户是未登录，应该跳转至登录页
  if(!token&&to.name!=='login'){
      next({name:'login'})
  }else if(token && to.name=="login"){   //token存在，说明用户登录，此时跳转至首页
      next({name:'home'})
  }else{
      next()
  }
})
// 后置路由守卫
router.afterEach((to,from)=>{
    document.title=to.meta.title||"商城后台管理系统"
})

export default router
